package com.ruoyi.sales.service.impl;

import java.util.Date;
import java.util.List;
import java.math.BigDecimal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.sales.mapper.SalesOrderMapper;
import com.ruoyi.sales.domain.SalesOrder;
import com.ruoyi.sales.domain.SalesOrderExecution;
import com.ruoyi.sales.service.ISalesOrderService;
import com.ruoyi.sales.service.ISalesOrderExecutionService;
import com.ruoyi.api.event.EventPublisher;
import com.ruoyi.api.event.OrderExecutionEvent;
import com.ruoyi.api.event.EventType;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.api.service.IStockService;
import com.ruoyi.api.dto.StockInventoryDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

/**
 * 销售订单主Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-06-17
 */
@Service
public class SalesOrderServiceImpl implements ISalesOrderService 
{
    private static final Logger logger = LoggerFactory.getLogger(SalesOrderServiceImpl.class);

    @Autowired
    private SalesOrderMapper salesOrderMapper;
    
    @Autowired
    private ISalesOrderExecutionService salesOrderExecutionService;
    
    @Autowired
    private EventPublisher eventPublisher;
    
    @Autowired(required = false)
    private IStockService stockService;

    /**
     * 查询销售订单主
     * 
     * @param orderId 销售订单主主键
     * @return 销售订单主
     */
    @Override
    public SalesOrder selectSalesOrderByOrderId(Long orderId)
    {
        return salesOrderMapper.selectSalesOrderByOrderId(orderId);
    }

    /**
     * 查询销售订单主列表
     * 
     * @param salesOrder 销售订单主
     * @return 销售订单主
     */
    @Override
    public List<SalesOrder> selectSalesOrderList(SalesOrder salesOrder)
    {
        return salesOrderMapper.selectSalesOrderList(salesOrder);
    }

    /**
     * 新增销售订单主
     * 
     * @param salesOrder 销售订单主
     * @return 结果
     */
    @Override
    @Transactional
    public int insertSalesOrder(SalesOrder salesOrder)
    {
        // 新增订单默认为待审核状态
        salesOrder.setOrderStatus("0"); // 订单状态为待审核
        salesOrder.setAuditStatus("0"); // 审核状态为未审核
        
        // 如果有库存服务，则检查库存
        if (stockService != null && salesOrder.getProductId() != null && salesOrder.getQuantity() != null)
        {
            // 检查商品库存是否足够
            boolean isStockSufficient = stockService.checkStockSufficient(
                    salesOrder.getProductId(), salesOrder.getQuantity());
            
            if (!isStockSufficient)
            {
                // 获取当前库存信息，用于展示给用户
                StockInventoryDTO inventory = stockService.getInventoryByProductId(salesOrder.getProductId());
                Long currentQuantity = inventory != null ? inventory.getCurrentQuantity() : 0L;
                
                throw new ServiceException(String.format("商品【%s】库存不足，当前库存: %d，需要: %d", 
                    salesOrder.getProductName(), currentQuantity, salesOrder.getQuantity()));
            }
        }
        
        return salesOrderMapper.insertSalesOrder(salesOrder);
    }

    /**
     * 修改销售订单主
     * 
     * @param salesOrder 销售订单主
     * @return 结果
     */
    @Override
    public int updateSalesOrder(SalesOrder salesOrder)
    {
        return salesOrderMapper.updateSalesOrder(salesOrder);
    }

    /**
     * 批量删除销售订单主
     * 
     * @param orderIds 需要删除的销售订单主主键
     * @return 结果
     */
    @Override
    public int deleteSalesOrderByOrderIds(String orderIds)
    {
        return salesOrderMapper.deleteSalesOrderByOrderIds(Convert.toStrArray(orderIds));
    }

    /**
     * 删除销售订单主信息
     * 
     * @param orderId 销售订单主主键
     * @return 结果
     */
    @Override
    public int deleteSalesOrderByOrderId(Long orderId)
    {
        return salesOrderMapper.deleteSalesOrderByOrderId(orderId);
    }
    
    /**
     * 审核通过销售订单
     * 
     * @param orderId 订单ID
     * @param auditOpinion 审核意见
     * @return 结果
     */
    @Override
    public int approveOrder(Long orderId, String auditOpinion)
    {
        SalesOrder order = selectSalesOrderByOrderId(orderId);
        order.setOrderStatus("1"); // 设置订单状态为已审核
        order.setAuditStatus("1"); // 设置审核状态为审核通过
        order.setAuditOpinion(auditOpinion);
        order.setUpdatedBy(ShiroUtils.getLoginName());
        return updateSalesOrder(order);
    }
    
    /**
     * 审核拒绝销售订单
     * 
     * @param orderId 订单ID
     * @param auditOpinion 审核意见
     * @return 结果
     */
    @Override
    public int rejectOrder(Long orderId, String auditOpinion)
    {
        SalesOrder order = selectSalesOrderByOrderId(orderId);
        order.setOrderStatus("1"); // 订单状态改为已审核
        order.setAuditStatus("2"); // 设置审核状态为审核不通过
        order.setAuditOpinion(auditOpinion);
        order.setUpdatedBy(ShiroUtils.getLoginName());
        return updateSalesOrder(order);
    }
    
    /**
     * 执行销售订单
     * 
     * @param orderId 订单ID
     * @param executionRemark 执行备注
     * @return 结果
     */
    @Override
    @Transactional
    public int executeOrder(Long orderId, String executionRemark)
    {
        // 默认使用账户ID为1的账户
        return executeOrder(orderId, executionRemark, 1L);
    }
    
    @Override
    @Transactional
    public int executeOrder(Long orderId, String executionRemark, Long accountId)
    {
        // 1. 获取订单信息
        SalesOrder order = selectSalesOrderByOrderId(orderId);
        if (order == null || !"1".equals(order.getAuditStatus()))
        {
            // 只有审核通过的订单才能执行
            return 0;
        }
        
        // 2. 更新订单状态为已执行
        order.setOrderStatus("2"); // 订单状态改为已执行
        order.setUpdatedBy(ShiroUtils.getLoginName());
        int rows = updateSalesOrder(order);
        
        if (rows > 0)
        {
            // 3. 添加订单执行记录
            SalesOrderExecution execution = new SalesOrderExecution();
            execution.setOrderId(orderId);
            execution.setExecutionDate(DateUtils.getNowDate());
            execution.setExecutor(ShiroUtils.getLoginName());
            execution.setExecutionRemark(executionRemark);
            execution.setCreatedTime(DateUtils.getNowDate());
            salesOrderExecutionService.insertSalesOrderExecution(execution);
            
            // 4. 发布销售订单执行事件，而不是直接调用财务服务
            OrderExecutionEvent event = new OrderExecutionEvent(EventType.SALES_ORDER_EXECUTED, orderId);
            event.setOrderCode(order.getOrderCode());
            event.setTotalAmount(order.getTotalAmount());
            
            // 添加商品信息，便于库存模块直接获取
            event.setProductId(order.getProductId());
            event.setProductName(order.getProductName());
            event.setQuantity(order.getQuantity());
            
            event.addData("customerId", order.getCustomerId());
            // 添加账户ID
            event.addData("accountId", accountId);
            eventPublisher.publishEvent(event);
        }
        
        return rows;
    }

    /**
     * 批量审核通过销售订单
     * 
     * @param orderIds 订单ID数组
     * @param auditOpinion 审核意见
     * @return 结果
     */
    @Override
    public int batchApproveOrders(String orderIds, String auditOpinion) {
        String[] ids = Convert.toStrArray(orderIds);
        int successCount = 0;
        
        for (String orderId : ids) {
            try {
                Long id = Long.valueOf(orderId);
                int result = approveOrder(id, auditOpinion);
                if (result > 0) {
                    successCount++;
                }
            } catch (Exception e) {
                logger.error("批量审核通过订单失败，订单ID: " + orderId, e);
            }
        }
        
        return successCount;
    }
    
    /**
     * 批量审核拒绝销售订单
     * 
     * @param orderIds 订单ID数组
     * @param auditOpinion 审核意见
     * @return 结果
     */
    @Override
    public int batchRejectOrders(String orderIds, String auditOpinion) {
        String[] ids = Convert.toStrArray(orderIds);
        int successCount = 0;
        
        for (String orderId : ids) {
            try {
                Long id = Long.valueOf(orderId);
                int result = rejectOrder(id, auditOpinion);
                if (result > 0) {
                    successCount++;
                }
            } catch (Exception e) {
                logger.error("批量审核拒绝订单失败，订单ID: " + orderId, e);
            }
        }
        
        return successCount;
    }
    
    /**
     * 批量执行选中的销售订单
     * 
     * @param orderIds 订单ID字符串，多个ID用逗号分隔
     * @param executionRemark 执行备注
     * @param accountId 财务账户ID
     * @return 成功执行的订单数量
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchExecuteOrders(String orderIds, String executionRemark, Long accountId) {
        if (accountId == null) {
            logger.error("批量执行销售订单失败：账户ID不能为空");
            throw new RuntimeException("账户ID不能为空");
        }
        
        if (StringUtils.isEmpty(orderIds)) {
            logger.error("批量执行销售订单失败：未选择要执行的订单");
            throw new RuntimeException("未选择要执行的订单");
        }
        
        String[] orderIdArray = Convert.toStrArray(orderIds);
        logger.info("开始批量执行销售订单，共{}个订单", orderIdArray.length);
        
        int successCount = 0;
        StringBuilder errorMsgs = new StringBuilder();
        
        // 逐个执行订单
        for (String orderIdStr : orderIdArray) {
            try {
                Long orderId = Long.parseLong(orderIdStr);
                // 检查订单是否审核通过
                SalesOrder order = selectSalesOrderByOrderId(orderId);
                if (order != null && "1".equals(order.getAuditStatus())) {
                    int result = executeOrder(orderId, executionRemark, accountId);
                    if (result > 0) {
                        successCount++;
                        logger.info("销售订单执行成功：ID={}, 编号={}", order.getOrderId(), order.getOrderCode());
                    } else {
                        logger.warn("销售订单执行失败：ID={}, 编号={}", order.getOrderId(), order.getOrderCode());
                        errorMsgs.append("订单[").append(order.getOrderCode()).append("]执行失败; ");
                    }
                } else {
                    errorMsgs.append("订单ID[").append(orderId).append("]未审核通过或不存在; ");
                }
            } catch (Exception e) {
                logger.error("执行销售订单异常：ID={}, 错误={}", orderIdStr, e.getMessage(), e);
                errorMsgs.append("订单ID[").append(orderIdStr).append("]执行异常: ").append(e.getMessage()).append("; ");
                // 继续执行下一个订单
            }
        }
        
        if (errorMsgs.length() > 0 && successCount < orderIdArray.length) {
            logger.warn("部分销售订单执行失败：{}", errorMsgs.toString());
        }
        
        logger.info("批量执行销售订单完成，成功{}个，失败{}个", 
                successCount, orderIdArray.length - successCount);
        
        return successCount;
    }
}
